home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1054 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  42 lines

  1. Newsgroups: comp.lang.c
  2. Path: gail.ripco.com!mambuhl
  3. From: mambuhl@ripco.com (Martin Ambuhl)
  4. Subject: Re: pseudo-random numbers
  5. X-Nntp-Posting-Host: foley.ripco.com
  6. Message-ID: <DL02pB.H7C@rci.ripco.com>
  7. Sender: usenet@rci.ripco.com (Net News Admin)
  8. Organization: Ripco Internet BBS Chicago
  9. Date: Thu, 11 Jan 1996 04:48:47 GMT
  10. X-Ident-Sender: mambuhl
  11.  
  12. JJSTEP00@ukcc.uky.edu (Jason Stephenson)
  13. in <17709D420S86.JJSTEP00@ukcc.uky.edu> asks:
  14.  
  15. >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
  16. >I seem to get "better" results with "rand() % n + 1" than I get when I use
  17. >"n * rand() / RAND_MAX + 1"  Am I missing some parenthesis or something?
  18.  
  19. Yes.
  20.  
  21. You might find these macros useful:
  22. #define random(num)     (int)(((long)rand()*(num))/(RAND_MAX+1))
  23. #define randomize()     srand((unsigned)time(NULL))
  24.  
  25. Notice that the macro random(num) evaluates to a value in the range
  26. 0...num-1.  You should restrict num to the range of an int.
  27.  
  28. Also, you could rewrite the macro so it returns a double
  29. #define halfopen_random()   ((double)rand()/(RAND_MAX+1))  /* [0,1) */
  30. #define closed_random()     ((double)rand()/(RAND_MAX))    /* [0,1] */
  31.  
  32.  
  33.  
  34. >Oh yeah, and I usually call "srand(clock())" once in the initialization of
  35. >my program.  With the first, I get an integer between 1 and n.  With the
  36. >second, I almost always get a value of 1 or 2.
  37.  
  38.                  
  39. --
  40. * Martin Ambuhl       net: mambuhl@ripco.com
  41. * Chicago, IL (USA)    
  42.